﻿using SH.Common.CommonReturn;
using SH.Common.DataDictionary;
using SH.Room.Infrastructure.IRepository;
using SqlSugar;
using System.Linq.Expressions;

namespace SH.Room.Infrastructure.Repository
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class, new()
    {
        private readonly ISqlSugarClient _context;

        public BaseRepository(ISqlSugarClient context)
        {
            _context = context;
        }

        //泛型属性：获取所有的
        public ISugarQueryable<T> All => _context.Queryable<T>();
        #region 同步
        //增
        public int Insert(T t)
        {
            var result = _context.Insertable(t).ExecuteCommand();
            return result;
        }
        //批量增
        public int BatchInsert(List<T> list)
        {
            var result = _context.Insertable<T>(list).ExecuteCommand();
            return result;
        }
        //删
        public int Delete(T t)
        {
            var result = _context.Deleteable(t).ExecuteCommand();
            return result;
        }
        //批量删除
        public int BatchDelete(List<T> list)
        {
            var result = _context.Deleteable<T>(list).ExecuteCommand();
            return result;
        }
        //改
        public int Upd(T t)
        {
            var result = _context.Updateable(t).ExecuteCommand();
            return result;
        }
        //批量修改
        public int BatchUpd(List<T> list)
        {
            var result = _context.Updateable<T>(list).ExecuteCommand();
            return result;
        }
        //查
        public List<T> GetList()
        {
            var list = _context.Queryable<T>().ToList();
            return list;
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="list">要分页的列表（ISugarQueryable<T>）</param>
        /// <param name="where">查询表达式树</param>
        /// <param name="orderBy">分页字符串 例：Price asc,CreateTime desc </param>
        /// <param name="pageSize">页容量</param>
        /// <param name="pageIndex">页码</param>
        /// <returns>返回公共分页DTO</returns>
        public ApiPaging<List<T>> PageQuery(ISugarQueryable<T> list, Expression<Func<T, bool>>? where, string? orderBy, int pageSize, int pageIndex)
        {
            //int pageNumber = 1;
            int totalCount = 0;
            int pageCount = 0;
            list = list.Where(where);
            if (!string.IsNullOrEmpty(orderBy))
            {
                list = list.OrderBy(orderBy);
            }
            var pageList = list.ToPageList(pageIndex, pageSize, ref totalCount, ref pageCount);
            return new ApiPaging<List<T>>() { Data = pageList, PageCount = pageCount, TotalCount = totalCount };
        }
        /// <summary>
        /// 根据条件获取实体 类似EF FirstOrDefault()
        /// </summary>
        /// <param name="where">查询表达式树</param>
        /// <returns>实体</returns>
        public T GetModelByCondition(Expression<Func<T, bool>> where)
        {
            return _context.Queryable<T>().First(where);
        }
        /// <summary>
        /// 根据条件获取集合 类似EF Where()
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public List<T> GetListByCondition(Expression<Func<T, bool>> where)
        {
            return _context.Queryable<T>().Where(where).ToList();
        }

        #endregion

        #region 异步
        //增
        public async Task<int> InsertAsync(T t)
        {
            var result = await _context.Insertable(t).ExecuteCommandAsync();
            return result;
        }
        //批量增
        public async Task<int> BatchInsertAsync(List<T> list)
        {
            var result = await _context.Insertable<T>(list).ExecuteCommandAsync();
            return result;
        }
        //查
        public async Task<List<T>> GetListAsync()
        {
            var list = await _context.Queryable<T>().ToListAsync();
            return list;
        }
        //分页
        public async Task<ApiPaging<List<T>>> PageQueryAsync(ISugarQueryable<T> list, Expression<Func<T, bool>>? where, string? orderBy, int pageSize, int pageIndex)
        {
            //int pageNumber = 1;
            RefAsync<int> totalCount = 0;
            RefAsync<int> pageCount = 0;
            list = list.Where(where);
            if (!string.IsNullOrEmpty(orderBy))
            {
                list = list.OrderBy(orderBy);
            }
            var pageList = await list.ToPageListAsync(pageIndex, pageSize, totalCount, pageCount);
            return new ApiPaging<List<T>>() { Data = pageList, PageCount = pageCount, TotalCount = totalCount };
        }
        //Expression<>获取实体
        public async Task<T> GetModelByConditionAsync(Expression<Func<T, bool>> where)
        {
            return await _context.Queryable<T>().FirstAsync(where);
        }
        //Expression<>获取集合
        public async Task<List<T>> GetListByConditionAsync(Expression<Func<T, bool>> where)
        {
            return await _context.Queryable<T>().Where(where).ToListAsync();
        }

        //多租户开启事务
        public virtual async void MultitenantBeginTranAsync()
        {
            await _context.AsTenant().BeginTranAsync();
        }
        //多租户提交事务
        public virtual async void MultitenantCommitAsync()
        {
            await _context.AsTenant().CommitTranAsync();
        }
        //多租户回滚
        public virtual async void MultitenantRollBackAsync()
        {
            await _context.AsTenant().RollbackTranAsync();
        }
        #endregion

        public List<Dic> GetDics()
        {
            return _context.AsTenant().QueryableWithAttr<Dic>().AS("shmultitenantdb.dic").ToList();
        }
    }
}
